package com.zhht.checkcop.exception;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

import com.zhbc.framework.support.Result;


/**
 * Project: 统一异常处理
 * <p/>
 * Title: OmsExceptionHandlerExceptionResolver
 * <p/>
 * Description:
 * <p/>
 * Date: 
 */
public class OpenExceptionHandlerExceptionResolver extends ExceptionHandlerExceptionResolver {
	
	protected static final Logger logger = Logger.getLogger(OpenExceptionHandlerExceptionResolver.class);
	
    @Override
    protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request, HttpServletResponse response,
                                                           HandlerMethod handlerMethod, Exception exception) {

        // ajax json 异常
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/plain; charset=utf-8");
           
            // 参数校验异常
            if (exception.getClass() == ValidationException.class) {
            	logger.error(exception.getMessage());
                ValidationException validationException = (ValidationException) exception;

                // 直接给出描述的，使用给出的描述
                if (validationException.getPrompt() != null && !"".equals(validationException.getPrompt().trim())) {
                	
                	Result r = new Result();
                	String json=r.error(validationException.getPrompt());
                	response.getWriter().write(json);
                }
                exception.printStackTrace();
                // 参数为空异常
                if (validationException.getType() == ValidationException.EMPTY) {
                	Result r = new Result();
                	String json=r.error(validationException.getParaChineseName());
                	response.getWriter().write(json);
                }
            }else{
            	// r = new Result();
             	//String json=r.error("服务器异常");
             	//response.getWriter().write(json);
            	exception.printStackTrace();
            }
            
           
          
        } catch (Exception e) {
            //this.logException(e);
        } finally {
            logger.error("异常详情:", exception);
        }
        // 页面异常,需要放在最后，否则不先解析ajax异常
        if (request.getRequestURI().contains("/jsp")) {
            return super.doResolveHandlerMethodException(request, response, handlerMethod, exception);
        }
        return new ModelAndView();
    }

 

}
